package com.matt.service.impl;

import com.google.common.collect.Lists;
import com.matt.domain.AppSkin;
import com.matt.repository.AppSkinRepository;
import com.matt.service.AppSkinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;


@Service
public class AppSkinServiceImpl implements AppSkinService {

    @Autowired
    AppSkinRepository appSkinRepository;

    @Override
    public Page<AppSkin> getPage(String areaId, Integer pageNum, Integer pageSize) {

        Specification<AppSkin> specification = new Specification<AppSkin>() {
            @Override
            public Predicate toPredicate(Root<AppSkin> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();



                Predicate p1 = criteriaBuilder.and(criteriaBuilder.equal(root.get("areaId"), areaId));
                Predicate p2 = criteriaBuilder.or(criteriaBuilder.isNull(root.get("areaId")));

                //   predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("areaId"), areaId)));
             //   predicates.add(criteriaBuilder.or(criteriaBuilder.isNull(root.get("areaId"))));
                predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("deleted"), false)));
                predicates.add(criteriaBuilder.or(p1, p2));
                query.where(predicates.toArray(new Predicate[predicates.size()]));
                query.orderBy(criteriaBuilder.desc(root.get("orderNo")));
                return query.getRestriction();
            }
        };
        Page<AppSkin> page = appSkinRepository.findAll(specification, PageRequest.of(pageNum, pageSize));
        List<AppSkin> list = Lists.newArrayList();
        page.getContent().stream().forEach(o -> {
            list.add(o);
        });


        return new PageImpl(list, PageRequest.of(pageNum, pageSize), page.getTotalElements());
    }

    @Override
    public AppSkin getPersonalSkin(String areaId) {
        AppSkin skin = null;
        List<AppSkin> list = appSkinRepository.findAllByAreaIdAndIsPersonalOrderByOrderNoDesc(areaId,true);
        if(list.size() > 0){
            skin = list.get(0);
        }
        return skin;
    }
}
